<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          >搜索
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:mstr:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:mstr:edit']"
          >修改
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:mstr:remove']"
        >删除
        </el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['project:mstr:export']"
          >导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="exportExcel"
          v-hasPermi="['project:mstr:export']"
          >导出当前数据
        </el-button>
      </el-col>
      <!--      <el-col :span="2.2" style="position: absolute;right: 35px;top:0" >
        <Page style="margin-right: 0px " :current="queryParams.pageNum" :page-size="queryParams.pageSize"  :total="total" @on-change="pageChange" simple></Page>
      </el-col>-->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="mstrList"
      border
      id="test"
      stripe
      highlight-current-row
      :row-style="{ padding: '0px' }"
      :cell-style="{ padding: '0px' }"
      :header-row-style="{ padding: '0px' }"
      :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="采购属性"
        width="80"
        align="center"
        prop="cgType"
      />
      <el-table-column label="采购属性名称" width="110" prop="cgName" />
      <el-table-column
        label="有效标志"
        width="100"
        align="center"
        prop="cgFlag"
      >
        <template #default="scope">
          <el-switch
            v-model="scope.row.cgFlag"
            active-value="0"
            inactive-value="1"
            @change="handleCgFlag(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="创建人"
        width="100"
        align="center"
        prop="createBy"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更改人"
        width="85"
        align="center"
        prop="updateBy"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        width="150"
        show-tooltip-when-overflow
        show-overflow-tooltip
        prop="remark"
      />
      <el-table-column
        label="操作"
        align="center"
        width="120"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            style="height: 22px"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:mstr:edit']"
            >修改
          </el-button>
          <!--          <el-button
            size="mini"
            type="text"
            style="height: 22px"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:mstr:remove']"
          >删除
          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改采购属性对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购属性" label-width="110px" prop="cgType">
          <el-input v-model="form.cgType" placeholder="请输入采购属性" />
        </el-form-item>
        <el-form-item label="采购属性名称" label-width="110px" prop="cgName">
          <el-input v-model="form.cgName" placeholder="请输入采购属性名称" />
        </el-form-item>
        <el-form-item label="备注" label-width="110px" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="有效标志" label-width="110px">
          <el-radio-group v-model="form.cgFlag">
            <el-radio
              v-for="dict in cgFlagOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--    查询对话框-->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="720px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="12">
          <el-form-item label="采购属性" label-width="100px" prop="cgType">
            <el-input
              v-model="queryParams.cgType"
              placeholder="请输入采购属性"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购属性名称" label-width="100px" prop="cgName">
            <el-input
              v-model="queryParams.cgName"
              placeholder="请输入采购属性名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效标志" label-width="100px" prop="cgFlag">
            <el-select
              v-model="queryParams.cgFlag"
              placeholder="请选择有效标志"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in cgFlagOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建人" label-width="100px" prop="createBy">
            <el-input
              v-model="queryParams.createBy"
              placeholder="请输入创建人"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMstr,
  getMstr,
  delMstr,
  addMstr,
  updateMstr,
  exportMstr,
  changeCgFlag,
} from "@/api/project/mstr";
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  name: "CgMstr",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,

      openSearch: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购属性表格数据
      mstrList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 有效标志字典
      cgFlagOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        cgType: null,
        cgName: null,
        cgFlag: null,
        createBy: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cgType: [
          { required: true, message: "采购属性不能为空", trigger: "blur" },
        ],
        cgName: [
          { required: true, message: "采购属性名称不能为空", trigger: "blur" },
        ],
        cgFlag: [
          { required: true, message: "有效标志不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_flag").then((response) => {
      this.cgFlagOptions = response.data;
    });
  },
  mounted() {
    this.getList();
  },
  methods: {
    /** 查询采购属性列表 */
    async getList() {
      this.loading = true;
      await listMstr(this.queryParams).then((response) => {
        this.mstrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSearch = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cgId: null,
        cgType: null,
        cgName: null,
        cgFlag: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.cgId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购属性";
    },
    handleSearch() {
      this.reset();
      this.title = "查询采购属性";
      this.openSearch = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const cgId = row.cgId || this.ids;
      getMstr(cgId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购属性";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.cgId != null) {
            updateMstr(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMstr(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cgIds = row.cgId || this.ids;
      this.$confirm(
        '是否确认删除采购属性编号为"' + cgIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delMstr(cgIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有采购属性数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportMstr(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },

    exportExcel() {
      /* generate workbook object from table */
      let wb = XLSX.utils.table_to_book(document.querySelector("#test"));
      /* get binary string as output */
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "sheetjs.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

    handleCgFlag(row) {
      let text = row.cgFlag === "0" ? "启用" : "停用";

      this.$confirm('确认要"' + text + "吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return changeCgFlag(row.cgId, row.cgFlag);
        })
        .then(() => {
          this.getList();
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.cgFlag = row.cgFlag === "0" ? "1" : "0";
        });
    },
  },
};
</script>
